<?php

namespace app\common\service;

use GuzzleHttp\Client;
use think\facade\Log;
use think\exception\HttpException;

class TxService
{
    protected $client;
    protected $baseUrl = 'https://wer.codexfield.hk/tx/';

    public function __construct()
    {
        $this->client = new Client([
            'timeout' => 10, // 请求超时时间
            'verify' => true, // 启用 SSL 验证
        ]);
    }

    /**
     * 获取交易详情
     *
     * @param string $txHash 交易哈希（66位，以 0x 开头）
     * @return array 解码后的交易信息
     * @throws \Exception|\GuzzleHttp\Exception\GuzzleException
     */
    public function getTransaction(string $txHash): array
    {
        // 参数校验
        if (!preg_match('/^0x[a-fA-F0-9]{64}$/', $txHash)) {
            throw new \InvalidArgumentException('Invalid transaction hash format.');
        }

        $url = $this->baseUrl . $txHash;

        try {
            $response = $this->client->get($url);

            $statusCode = $response->getStatusCode(); // 200
            $body = $response->getBody()->getContents();

            if ($statusCode !== 200) {
                Log::error('TxService: HTTP Status Code ' . $statusCode, ['url' => $url, 'response' => $body]);
                throw new HttpException($statusCode, "Request failed with status $statusCode");
            }

            $data = json_decode($body, true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                Log::error('TxService: JSON Decode Error', ['body' => $body]);
                throw new \RuntimeException('Invalid JSON response from server.');
            }

            // 可以在这里对数据进行进一步处理或验证
            return $this->formatTransactionData($data);

        } catch (\Exception $e) {
            Log::error('TxService Error: ' . $e->getMessage(), [
                'tx_hash' => $txHash,
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            // 你可以选择重新抛出，或返回一个错误结构
            throw $e; // 或 return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    /**
     * 格式化交易数据（可选）
     * 这里可以根据你的业务需求，对原始数据进行加工
     */
    private function formatTransactionData(array $data): array
    {
        // 例如：将 gasPrice 和 value 转换为 ETH 单位
        if (isset($data['gasPrice'])) {
            $data['gasPriceEth'] = $this->weiToEth($data['gasPrice']);
        }
        if (isset($data['value'])) {
            $data['valueEth'] = $this->weiToEth($data['value']);
        }
        if (isset($data['gasUsed']) && isset($data['gasPrice'])) {
            $totalGasFeeWei = $data['gasUsed'] * $data['gasPrice'];
            $data['totalGasFeeEth'] = $this->weiToEth($totalGasFeeWei);
        }

        // 确保布尔值正确
        $data['success'] = !empty($data['status']) && $data['status'] == 1;

        return $data;
    }

    /**
     * 将 Wei 转换为 ETH
     */
    private function weiToEth(string|int $wei): float
    {
        return round($wei / 1e18, 8);
    }
}